(define
    (random-ints count)
    (if (= 0 count)
        '()
        (cons count (random-ints (- count 1)))
    )
)

(define
    (list-head pull-from k)
    (if (= 0 k)
        '()
        (cons (car pull-from) (list-head (cdr pull-from) (- k 1)))
    )
)

(define
    (quicksort to-sort)
    (if (null? to-sort)
        '()
        (let
            (
                (pivot (car to-sort))
                (le-list '())
                (gt-list '())
            )
            (do
                (
                    (left (cdr to-sort) (cdr left))
                )
                ((null? left)
                    (append (quicksort le-list) (list pivot) (quicksort gt-list))
                )
                (let*
                    (
                        (considering (car left))
                        (considering-list (list considering))
                    )
                    (if (<= considering pivot)
                        (set! le-list (append le-list considering-list))
                        (set! gt-list (append gt-list considering-list))
                    )
                )
            )
        )
    )
)

(define
    (mergesort first-half last-half)
    (cond
        ((null? first-half) last-half)
        ((null? last-half) first-half)
        (else
            (let
                (
                    (first-half-item (car first-half))
                    (last-half-item (car last-half))
                )
                (if (<= first-half-item last-half-item)
                    (cons
                        first-half-item
                        (mergesort (cdr first-half) last-half)
                    )
                    (cons
                        last-half-item
                        (mergesort first-half (cdr last-half))
                    )
                )
            )
        )
    )
)

(define
    (display-list-helper num-list)
    (let
        (
            (num-str (number->string (car num-list)))
            (rest (cdr num-list))
        )
        (if (null? rest)
            (display num-str)
            (begin
                (display (string-append num-str ", "))
                (display-list-helper rest)
            )
        )
    )
)

(define
    (display-list num-list)
    (begin
        (display "[")
        (display-list-helper num-list)
        (display "]")
    )
)


; Main --------------------------------
(let*
    (
        (int-count (string->number (list-ref (command-line-arguments) 0)))
        (mid-point (inexact->exact (floor (/ int-count 2))))
        (random-list (random-ints int-count))
        (first-half (list-head random-list mid-point))
        (last-half (list-tail random-list mid-point))
        (sorted-first (quicksort first-half))
        (sorted-last (quicksort last-half))
    )
    (display-list (mergesort sorted-first sorted-last))
    (newline)
)
